/*
 * Copyright (C) 2018 Ortega Froysa, Nicolás <nortega@themusicinnoise.net>
 * Author: Ortega Froysa, Nicolás <nortega@themusicinnoise.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Model.hpp"

#include <GL/glew.h>
#include <GL/gl.h>

Model::Model(const std::vector<struct Vertex> &vertices,
		const std::vector<unsigned int> &indices) :
	vertices(vertices), indices(indices)
{
	glGenVertexArrays(1, &vao);
	glGenBuffers(1, &vbo);
	glGenBuffers(1, &ebo);

	glBindVertexArray(vao);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER,
			vertices.size() * sizeof(struct Vertex),
			&vertices[0], GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER,
			indices.size() * sizeof(unsigned int),
			&indices[0], GL_STATIC_DRAW);

	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
			sizeof(struct Vertex), nullptr);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
			sizeof(struct Vertex),
			(void*)offsetof(struct Vertex, normal));
	glBindVertexArray(0);
}

void Model::draw(const Shader &shader) {
	glUniform3f(
			glGetUniformLocation(shader.getId(), "col"),
			color.r, color.g, color.b);
	glBindVertexArray(vao);
	glDrawElements(GL_TRIANGLES, indices.size(),
			GL_UNSIGNED_INT, 0);
	glBindVertexArray(0);
}
